<?php
namespace api\modules\mp\models;

use common\tool\Curd;
use yii\base\Model;
use yii\web\NotFoundHttpException;

class Comment extends Model {

    use Curd;
    public static function tableName() {
        return 'mp_comment';
    }
    public function rules() {
        return [
            [
                'resourceId',
                'number'
            ],
            [
                'type',
                'in',
                'range' => [
                    self::TYPE_COMPANION,
                    self::TYPE_TRANSFER,
                    self::TYPE_BOAT
                ]
            ],
            [
                'pid',
                'number'
            ],
            [
                'content',
                'string',
                'min' => 2
            ],
            [
                'openid',
                'string'
            ],
        ];
    }
    public function attributeLabels() {
        return ['content'=>'评论内容',];
    }

    public $id;
    public $type = self::TYPE_COMPANION;//所属资源类型
    public $resourceId;//所属资源id
    public $openid;
    public $pid = 0;//0为评论,1为回复
    public $content;
    public $ctime;
    const TYPE_COMPANION = 1;
    const TYPE_TRANSFER = 2;
    const TYPE_BOAT = 3;

    public static function build($data = []): ?self {
        if (!empty($data['id'])) {
            $one = self::getOne("id={$data['id']}");
            if (!$one) throw new NotFoundHttpException();
            $data = array_merge($one, $data);
        }
        return new self($data);
    }
    
    public function save() {
        $now = date('Y-m-d H:i:s');
        $data = [
            'type' => $this->type,
            'resource_id' => $this->resourceId,
            'pid' => $this->pid,
            'openid' => $this->openid,
            'content' => $this->content,
            'ctime' => $now,
        ];
        $id = self::insert($data);
        $this->id = $id;
        $this->ctime = $now;
    }

    public function info() {
        return $this->getAttributes();
    }
}
